//
//  TestView.m
//  JackToolsBox
//
//  Created by Jack Xue on 2019/12/5.
//  Copyright © 2019 Jack Xue. All rights reserved.
//

#import "JKTagView.h"
#import "CheckStruct.h"
#define JK_MAIN_WIDTH [UIScreen mainScreen].bounds.size.width
#define JK_ITEM_HEIGHT 20   //每个tag的高度
#define JK_FONT_SIZE 15     //字体大小
#define JK_ITEM_SPACING 8.0 //间距

@interface JKTagView(){
    NSArray <JkTagItem*>*_itemsArray;
    CGFloat _changedHeight;                 //autolayout改变view高度
    CheckRect _checkRect;
}
@property(nonatomic,strong)NSMutableArray *rectArray;
@end

@implementation JKTagView
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    NSLog(@"layoutSubviews --- %@",NSStringFromCGRect(self.frame));
}

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    /*
     layoutSubviews执行后，autolayout已经转换成正确的frame
     重绘的方法只能在这里使用
     */
    NSLog(@"drawRect---%@",NSStringFromCGRect(rect));
    for (NSInteger i = 0; i < self.rectArray.count; i++) {
        NSValue *value = self.rectArray[i];
        JkTagItem *model = _itemsArray[i];
        NSString *item = model.titleString;
        CGRect sendRect = [value CGRectValue];
        [self jkRendeming:item rect:sendRect];
    }
}

#pragma mark - 绘制item
-(void)jkRendeming:(NSString*)item rect:(CGRect)rect{
    //1.先绘制外边框
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:3];
    path.lineWidth = 1;
    [self.frontColor setStroke];
    [path stroke];
    
    //2.绘制文字
    NSMutableParagraphStyle *textStyle = [NSMutableParagraphStyle new];
    textStyle.alignment = NSTextAlignmentCenter;
    [item drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:JK_FONT_SIZE],NSParagraphStyleAttributeName:textStyle,NSForegroundColorAttributeName:self.frontColor}];
}

-(void)setDataSourceArray:(NSArray<JkTagItem *> *)array{
    _itemsArray = array;
    NSLog(@"计算时的宽度%.2f",self.bounds.size.width);
    //计算每个item的尺寸，然后提前设置self.height
    CGFloat height = JK_ITEM_HEIGHT + JK_ITEM_SPACING;
    CGFloat widthRec = 0, heightRec = 0;

    for (NSInteger i = 0; i < array.count; i++) {
        JkTagItem *model = array[i];
        NSString *itemString = model.titleString;
        CGSize stringSize = [itemString boundingRectWithSize:CGSizeMake(MAXFLOAT, JK_ITEM_HEIGHT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:JK_FONT_SIZE]} context:nil].size;
        CGSize recSize = CGSizeMake(stringSize.width + JK_ITEM_SPACING*2, JK_ITEM_HEIGHT);
        CGRect recRect = CGRectMake(widthRec + JK_ITEM_SPACING, heightRec + JK_ITEM_SPACING, recSize.width, recSize.height);
        //如果item右边超过最大界限则换行
        if (recRect.origin.x + recRect.size.width > self.bounds.size.width) {
            recRect.origin.x = JK_ITEM_SPACING;
            heightRec = recRect.origin.y + recRect.size.height;
            recRect.origin.y = heightRec + JK_ITEM_SPACING;
            height += (JK_ITEM_HEIGHT + JK_ITEM_SPACING);
        }
//        NSLog(@"尺寸%@",NSStringFromCGRect(recRect));
        NSValue *recValue = [NSValue valueWithCGRect:recRect];
        [self.rectArray addObject:recValue];
        widthRec = recRect.origin.x + recRect.size.width;
    }
    
    //确定自身高度
    CGRect newRect = self.frame;
    newRect.size.height = height + JK_ITEM_SPACING;
    self.frame = newRect;
    
}

#pragma mark - 点击事件处理
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    if ([self.delegate respondsToSelector:@selector(didSelectedTagWithIndex:item:)]) {
        //不涉及到多点触控，只需取一个touch就可以
        CGPoint touchPoint = [[[touches allObjects]firstObject] locationInView:self];
        
        for (NSInteger i = 0; i < self.rectArray.count; i++) {
            NSValue *value = self.rectArray[i];
            CGRect sendRect = [value CGRectValue];
            if (CGRectContainsPoint(sendRect, touchPoint) ) {
                _checkRect.rect = sendRect;
                _checkRect.index = i;
                break;  //结束循环
            }
        }
    }//@end - 判断用户是否需要获取点击事件
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    if ([self.delegate respondsToSelector:@selector(didSelectedTagWithIndex:item:)]) {
        CGPoint endPoint = [[[touches allObjects]firstObject] locationInView:self];
        if (CGRectContainsPoint(_checkRect.rect, endPoint)) {
            [self.delegate didSelectedTagWithIndex:_checkRect.index item:_itemsArray[_checkRect.index]];
        }
    }
}

#pragma mark - 懒加载
-(UIColor *)frontColor{
    //默认白色
    if (!_frontColor) {
        _frontColor = [UIColor blackColor];
    }
    return _frontColor;
}

-(NSMutableArray *)rectArray{
    if (!_rectArray) {
        _rectArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _rectArray;
}



@end
